<?php namespace App\Api\Http\ApiControllers;

use App\Exceptions\OtherException;
use App\Repositories\Item\CompanyRepositoryInterface;
use Illuminate\Http\Request;

class PublisherCompanyController extends Controller
{
    /**
     * @var CompanyRepositoryInterface
     */
    protected $company_repository;

    public function __construct(
        CompanyRepositoryInterface $company_repository
    ) {
        $this->company_repository = $company_repository;
    }

    public function show($id)
    {
        $company = $this->company_repository->show((int)$id);
        throw_unless($company, new OtherException('公司不存在'));

        throw_if($company->creator_uid != access()->id(), new OtherException('没有权限查看'));

        return response()->json($company->toArray());
    }

    public function store(Request $request)
    {
        $user_id = access()->id();
        $name = $request->get('name');
        throw_if(mb_strlen($name) < 2, new OtherException('公司名称填写错误'));

        $model = $this->company_repository->store($user_id, $name);

        return response()->json($model->only(['id', 'name']), 201);
    }

    public function update($id, Request $request)
    {
        $user_id = access()->id();
        $name = $request->get('name');
        throw_if(mb_strlen($name) < 2, new OtherException('公司名称填写错误'));

        $this->company_repository->update($id, $name, $user_id);

        return response('', 204);
    }
}
